//
//  AppDelegate.swift
//  JSTech
//
//  Created by 高得华 on 2019/9/29.
//  Copyright © 2020 华&梅. All rights reserved.
//

import UIKit
import AdSupport//广告

///OpenInstallSDK 的 保存的key
fileprivate let kMMOpenInstallSDKKey = "_openInstallSDK+123"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    ///Https的配置信息及 隐私政策、用户协议
    @objc dynamic var dataHttps = MMConfigModel() {
        didSet {///配置网络信息
            self._configureHttp()
        }
    }
    /// - ==== H5相关的链接
    ///隐私政策
    @objc var article_privacy = ""
    ///行为规范
    @objc var article_penalties = ""
    ///绿色公约
    @objc var article_gongyue = ""
    ///用户协议
    @objc var article_agreement = ""
    
    ///跳转到 APP 中 URLScheme
    var curAppUrlScheme = ""
    ///推送相关的数据
    var notificationData: [AnyHashable : Any]?
    ///窗口
    var window: UIWindow?
    ///消息未读数量
    @objc dynamic var unReadMesNum: Int = 0
    ///陌生私聊的未读数
    @objc dynamic var unReadStrangeMesNum: Int32 = 0
    /// APP的网络服务层
    @objc var services: MDHViewModelServicesImpl {
        get {
            return MDHRouter.sharedInstance().services
        }
    }
    /// APP管理的导航栏的堆栈
    @objc var navigationControllerStack: MDHNavigationControllerStack {
        get {
            return MDHRouter.sharedInstance().navigationControllerStack
        }
    }
    ///deviceToken -> 用于推送
    fileprivate var deviceToken: Data!
    /// 公告接口 请求的数据
    @objc dynamic var dataIpv = MMIndexAppVersionModel()
    // 毛玻璃 安全遮盖
    fileprivate var viewEffect: UIVisualEffectView?
    ///IDFAString 广告ID
    @objc var IDFAString = ""
    ///是否已经激活青少年模式，与UserDefault一致，1:已经开启青少年模式，0:未开启青少年模式；在需要使用的地方进行监听，值改变即可改变
    @objc dynamic var isChildModeActived = false
    ///定时器的时间
    @objc var childModeActivedTime = 0
    ///是已经弹出了视图
    @objc dynamic var isChildModeAlertShow = false
    ///苹果内购的需要提示
    fileprivate var appleRechargeTimes = 0
    ///苹果内购 是否 正在请求网络
    fileprivate var isNetworkApple = false
    ///苹果支付是否出现了错误 需要
    @objc dynamic var isAppleError = false
    

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        ///魅力达人显示的key
        //kMDHUserDefaults().set(true, forKey: kMMGlamourJoinInKey)
        
        /// 广告ID//取出IDFA来
        let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
        self.IDFAString = ((idfa as NSString).md5() as NSString?)?.uppercased ?? idfa
        
        // Override point for customization after application launch.
        let wd = UIWindow.init(frame: UIScreen.main.bounds)
        wd.backgroundColor = UIColor.black
        // 让窗口可见
        wd.makeKeyAndVisible()
        //设置rootViewController
        let root_vc = UIStoryboard.init(name: "LaunchScreen", bundle: nil).instantiateViewController(withIdentifier: "ViewController")
        wd.rootViewController = root_vc
        self.window = wd
        
        /// 初始化UI之前配置
        self._configureApplication(application, didFinishLaunchingWithOptions: launchOptions)
        ///需要配置完 Https之后 再进行设置主界面
        /// 初始化UI后配置
        self._configureApplication(application, initialParamsAfterInitUI: launchOptions)
        
        #if DEBUG /// 调试模式
        self._configDebugModelTools()
        //[UMessage openDebugMode:YES];
        //[UMessage setWebViewClassString:@"UMWebViewController"];
        //[UMessage addLaunchMessage];
        ///启动时间
        //let launchTime = (CFAbsoluteTimeGetCurrent() - StartTime);
        //print("启动时间double======\(launchTime)");
        #else
        ///线上
        #endif
        
        ///UIApplicationShortcutItem.
        if #available(iOS 9.0, *) {
            let shortcutItem = launchOptions?[UIApplication.LaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem
            //如果是从快捷选项标签启动app，则根据不同标识执行不同操作，然后返回NO，防止调用- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
            if let item = shortcutItem {
                //判断先前我们设置的快捷选项标签唯一标识，根据不同标识执行不同操作
                self.dealWithShortcut(type: item.type)
            }
        } else {
            // Fallback on earlier versions
        }
        
        
        return true
    }

    /*
    // MARK: UISceneSession Lifecycle
    @available(iOS 13.0, *)
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    @available(iOS 13.0, *)
    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }
    */
}

//MARK: - ==== 其他信息 跳转等
extension AppDelegate {
    ///sharedDelegate AppDelegate
    @objc class func shared() -> AppDelegate? {
        return UIApplication.shared.delegate as? AppDelegate
    }
    ///最顶上的Nav
    @objc class func navigationController() -> UINavigationController {
        return MDHRouter.sharedInstance().navigationControllerStack.topNavigationController()
    }
    ///顶部视图
    @objc class func topViewController() -> UIViewController {
        return MDHRouter.sharedInstance().navigationControllerStack.topViewController()
    }
    ///跳转H5页面
    @objc class func pushToH5Vc(url: String, title: String = "", data: [String:Any] = [String:Any]()) -> () {
        #if DEBUG /// 调试模式
        
        #endif
        DispatchQueue.main.async {
            let isOk = MDHWKWebViewManager.share.push(url: url)
            if isOk {
                var viewStyle = -1
                var dict = data
                for (k, v) in dict {
                    if k == "viewStyle" {
                        let vStr = (v as? String ?? "")
                        viewStyle = (vStr as NSString).integerValue
                        dict.removeValue(forKey: k)
                        break
                    }
                }
                //dict["user_id"] = MDHSwiftHeader.userIdEncrypt()///对user_id进行加密
                dict["source"] = "ios"
                dict["app_device_id"] = MDHURLExtendsParameters().app_device_id

                let services = MDHRouter.sharedInstance().services
                let vm = MDHWebViewModel.init(services: services, params: dict)
                vm.viewStyle = viewStyle
                vm.url = url
                if title.isEmpty {
                    vm.title = kMMWPTFC().bundleName
                }else{
                    vm.title = title
                }
                vm.title = "加载中..."
                services.push(vm, animated: true)
                
                /*let vc = MDHWKWebViewController.init(viewModel: vm)
                var dJsonstr = ""
                if dict.count > 0 && viewStyle != -2 {
                    dJsonstr = (dict as NSDictionary).mj_JSONString()
                }
                vc.loadWebURLSring(url)
                //vc.postWebURLSring(url, postData: dJsonstr)
                AppDelegate.navigationController().pushViewController(vc, animated: true)*/
            }
        }
    }
    ///聊天发送消息
    @objc class func pushChatVc(user: MDHUserModel) -> () {
        self.pushChatViewController(model: user)
    }
    ///聊天界面中的数据
    @objc class func pushChatViewController(model: MDHUserModel) -> () {
        
    }
}


//MARK: - === 在初始化UI之前配置
extension AppDelegate {
    ///在初始化UI之前配置
    fileprivate func _configureApplication(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> () {
        ///配置网络请求的数据
        //self._configureHttp()
        /// 显示状态栏
        //application.setStatusBarHidden(false, with: UIStatusBarAnimation.fade)
        ///通知方面
        self._registNotification()
        /// 配置键盘
        self._configureKeyboardManager()
        /// 配置文件夹
        self._configureApplicationDirectory()
        /// 配置FMDB
        self._configureFMDB()
        ///腾讯方面
        self._configureTxIm_Bugly()
        ///友盟方面
        self._configureUPushParams(launchOptions: launchOptions)
        ///高德定位方面
        self._configureAMapLocationKit()
        ///ShareSDK方面
        self._configureShareSDK()
        #if arch(i386) || arch(x86_64)
        #else// 实人认证不支持模拟器调试
        ///人脸识别 //必须为RPSDKEnvOnline  RPSDKEnvDaily日常(不能使)
        //RPSDK.initialize(RPSDKEnv.online)
        ///DUEntry
        self._setupDUEntry()
        #endif
        ///配置内购
        self._configureSwiftyStoreKit()
        ///js交互
        self._showWeb_js()
        ///设置 推广专家
        //self.openInstallSDK(isInit: true)
        ///SDWebImage
        self._setupSDWebImage()
    }
    
    ///SDWebImage
    fileprivate func _setupSDWebImage() -> () {
        SDImageCodersManager.shared.addCoder(SDImageWebPCoder.shared)
        SDWebImageDownloader.shared.setValue("image/webp,image/*,*/*;q=0.8", forHTTPHeaderField:"Accept")
    }
    
    ///DUEntry
    fileprivate func _setupDUEntry() -> () {
        
    }
    
    ///数据 OpenInstallSDK
    func openInstallSDK(isInit: Bool = false) -> () {
        
    }
    
    /**
     * 安装时获取h5页面动态参数（如果是渠道链接，渠道编号会一起返回）
     * @param params 动态参数
     * @param error 错误回调
     * @discussion 老版本sdk升级过来可延用该api
     */
    func getInstallParams(fromOpenInstall params: [AnyHashable : Any]?, withError error: Error?) {
        
    }
    
    /// 配置网络请求的数据
    fileprivate func _configureHttp() -> () {
        let data = self.dataHttps
        ///基础的URL
        MDHHTTPService.setupBaseUrl(data.api_url)
        ///签名的key
        MDHHTTPService.setupSignKey(MHHTTPServiceSignKey)
        ///加密的私密
        MDHHTTPService.setupPrivateKey(MHHTTPServiceKeyValue)
        ///
        MDHHTTPService.setupRequestTokenKey(MHHTTPRequestTokenKey)
        ///
        MDHHTTPService.setupErrorResponseCodeKey(MHHTTPServiceErrorResponseCodeKey)
        ///
        MDHHTTPService.setupResponseMsgKey(MHHTTPServiceResponseMsgKey)
        //
        MDHHTTPService.setupResponseCodeKey(MHHTTPServiceResponseCodeKey)
        ///
        MDHHTTPService.setupResponseDataKey(MHHTTPServiceResponseDataKey)
        ///
        MDHHTTPService.setupResponseDataListKey(MHHTTPServiceResponseDataListKey)
        
        ///配置 页面跳转的信息
        kMMWPTFC().viewModelViewMappings()
        ///设置 推广专家
        self.openInstallSDK(isInit: true)

        ///h5域名
        let h5_ym = self.dataHttps.mobile_url
        ///h5域名拼接
        self.article_gongyue = h5_ym+"article/gongyue"
        self.article_agreement = h5_ym+"article/agreement"
        self.article_penalties = h5_ym+"article/penalties"
        self.article_privacy = h5_ym+"article/privacy"
        
        ///设置 主窗口
        MDHRouter.sharedInstance().navigationControllerStack.window = self.window

        // Config Service
        // 重置rootViewController
        //[self.services resetRootViewModel:[self _createInitialViewModel]];
        NotificationCenter.default.post(name: NSNotification.Name.init(kNotification_LoginSuccess), object: nil)
        /*
        // Save the application version info. must write last
        let version = kMDHInfoPlist().cfBundleShortVersionString
        kMDHUserDefaults().setValue(version, forKey: MHApplicationVersionKey)
        kMDHUserDefaults().synchronize()
        */
        
        ///快捷方式
        self.creatShortcutItem()
        
        ///微信浮窗
        //let vcname = MDHWKWebViewController.className()
        //FloatViewManager.manager.addFloatVcsClass(vcs: [vcname])
    }
    
    /// 配置FMDB
    fileprivate func _configureFMDB() -> () {
        
    }
    
    ///调试模式
    fileprivate func _configDebugModelTools() -> () {
          /*/// 显示FPS
          [[JPFPSStatus sharedInstance] open];
          
          /// 打开调试按钮
          [MHDebugTouchView sharedInstance];
          /// CoderMikeHe Fixed: 切换了根控制器，切记需要将指示器 移到window的最前面
          [self.window bringSubviewToFront:[MHDebugTouchView sharedInstance]];
          */
    }
    
    
    //MARK: - ===== 配置 友盟推送
    fileprivate func _configureUPushParams(launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> () {
        
        ///注册通知
        let settings = UIUserNotificationSettings.init(types: UIUserNotificationType.init(rawValue: UIUserNotificationType.sound.rawValue|UIUserNotificationType.alert.rawValue|UIUserNotificationType.badge.rawValue), categories: nil)
        UIApplication.shared.registerUserNotificationSettings(settings)
        UIApplication.shared.registerForRemoteNotifications()
    }
    
    /// - ===== 配置 腾讯云通信
    fileprivate func _configureTxIm_Bugly() -> () {
        
    }
    ///BuglyDelegate
    
    
    /// 配置 定位
    fileprivate func _configureAMapLocationKit() -> () {
        AMapServices.shared()?.apiKey = kAMapServicesAppKey
        kMMWPTFC().locationStart { (location, regeocode, error) in
            #if DEBUG
            print("- === 高德地址:\(String(describing: regeocode?.formattedAddress))")
            #endif
        }
    }
    
    /// 配置 SwiftyStoreKit
    fileprivate func _configureSwiftyStoreKit() -> () {
        
    }
    
    /// 配置 ShareSDK
    fileprivate func _configureShareSDK() -> () {
        /*! @brief WXApi的成员函数，向微信终端程序注册第三方应用。
        *
        * 需要在每次启动第三方应用程序时调用。
        * @attention 请保证在主线程中调用此函数
        * @param appid 微信开发者ID
        * @param universalLink 微信开发者Universal Link
        * @return 成功返回YES，失败返回NO。
        */
    }
    
    /// 配置文件夹
    fileprivate func _configureApplicationDirectory() -> () {
        /// 创建doc
        MHFileManager.createDirectory(atPath: MHWeChatDocDirPath())
        /// 创建cache
        MHFileManager.createDirectory(atPath: MHWeChatCacheDirPath())
        ///保存图片到临时文件
        let filePath = MHFilePathFromWeChatCache(MDHPT_MMW_TEMPVideo_NAME)
        let fileSize = MHFileManager.folderSize(atPath: filePath)
        #if DEBUG
        print("MHWeChatDocDirPath is [ \(String(describing: MHWeChatDocDirPath())) ] \n MHWeChatCacheDirPath is [ \(String(describing: MHWeChatCacheDirPath())) ]")
        print("视频的缓存文件大小- ==>:\(fileSize)")
        #endif
    }
    
    /// 配置键盘管理器
    fileprivate func _configureKeyboardManager() -> () {
       let iqsm = IQKeyboardManager.shared()
        iqsm.isEnabled = true
        iqsm.isEnableAutoToolbar = true
        iqsm.shouldResignOnTouchOutside = true
        iqsm.toolbarDoneBarButtonItemText = "完成"
        iqsm.toolbarTintColor = UIColor.black
    }
        
    /// - ==== 通知方面
    fileprivate func _registNotification() -> () {
        
        /*
         user_id <= 0:
         退出 Tim、友盟 关闭mqtt
         
         user_id > 0:
         登录 TIM/友盟 (没有mqtt数据->请求) -> 链接MQTT
         
         */
        
        ///通知中心
        let center = NotificationCenter.default
        ///监听切换根控制器的通知
        ///登录 退出
        center.rac_addObserver(forName: kNotification_LoginSuccess, object: nil)
            .deliverOnMainThread()
            .subscribeNext { [weak self] (note) in
                if let weakSelf = self {
                    let ser = weakSelf.services
                    //let vm = weakSelf._createInitialViewModel()
                    //ser.resetRootViewModel(vm)
                    ///ViewController
                    let vc = weakSelf._createInitialViewController()
                    ser.resetRootViewController(vc)
                    
                    
                    /*
                    let pw = kMDHUserDefaults().string(forKey: kMDHAdolescentUdKey) ?? ""
                    if pw.count > 0 {///青少年模式
                        let vm = MMAdolescentViewModel.init(services: ser, params: [AnyHashable : Any]())
                        ser.resetRootViewModel(vm)
                    }else{
                        let user = ser.client.currentUser()
                        if user.user_id <= 0 { /// 切换根控制器
                            /*///关闭socket
                            weakSelf.barrMan?.timer_dealloc()
                            kMDHCMMQ().close()
                            kMDHMQTT().close_manager()*/
                            let vm = weakSelf._createInitialViewModel()
                            ser.resetRootViewModel(vm)
                        }else{
                            //weakSelf.linkToThirdParties()
                            blockTimSdkLogin()
                        }
                        /// 切换了根控制器，切记需要将指示器 移到window的最前面
                        #if DEBUG
                                //[self.window bringSubviewToFront:[MHDebugTouchView sharedInstance]];
                        #endif
                    }*/
                }
        }
        
        ///监听 - Rac监听 消息数量
        self.rac_values(forKeyPath: "unReadMesNum", observer: self)
            .deliverOnMainThread().subscribeNext { [weak self] (x) in
                if let weakSelf = self {
                    if let root = weakSelf.window?.rootViewController {
                        
                    }
                }
        }
        
        ///监听 系统的 截图事件
        center.rac_addObserver(forName: UIApplication.userDidTakeScreenshotNotification.rawValue, object: self)
            .deliverOnMainThread()
            .subscribeNext { [weak self] (note) in
                if let weakSelf = self {
                    print("截图 - - - \(weakSelf)")
                }
        }
        
        /*///点击了推送消息
        kGMWEAKSELF
        [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:EBBannerViewDidClickNotification object:nil] deliverOnMainThread] subscribeNext:^(NSNotification * x) {
            [weakSelf notificationReceiveMessagePush:x.object];
        }];*/
     }
    
    /// - ==== 设置弹幕及重新获取弹幕信息
    @objc func linkToThirdParties() -> () {
        
    }
    
    /// - ==== 登录腾讯云IMSdk
    @objc func _timSdkRegister(isLogin: Bool = false) -> () {
        
    }
    
    /// - ==== 登录腾讯云IMSdk
    @objc func _timSdkLogin() -> () {
        
    }
    
    //MARK: - 创建根控制器
    ///创建根控制器
    fileprivate func _createInitialViewModel() -> MDHViewModel {
        let ser = self.services
        let params = [String: String]()
        return JSTDocListViewModel.init(services: ser, params: params)
    }
    
    ///创建根控制器
    fileprivate func _createInitialViewController() -> MDHViewController {
        let ser = self.services
        let params = [String: String]()
        return JSTTabbarViewController.init(services: ser, params: params)
    }
}


//MARK: - 初始化UI后配置
extension AppDelegate {
    ///初始化UI后配置
    fileprivate func _configureApplication(_ application: UIApplication, initialParamsAfterInitUI launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> () {
        ///TABAnimated
        TABAnimated.shared()?.initWithOnlySkeleton()
        //TABAnimated.shared()?.animatedColor = kColor_MDH8976CA()
        //TABAnimated.shared()?.shimmerBackColor = kColor_MDH8976CA()
        //TABAnimated.shared()?.animatedBackgroundColor = UIColor.white.withAlphaComponent(0.0001)
        //TABAnimated.shared().shimmer
        #if DEBUG /// 调试模式
        TABAnimated.shared()?.openLog = true
        #else
        TABAnimated.shared()?.openLog = false
        #endif
        
        /// 配置ActionSheet
        //[LCActionSheet mh_configureActionSheet];
        
        /// 预先配置平台信息
        //[SBUMengService configureUMengPreDefinePlatforms];
        
        //NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
        //@weakify(self);
        /// 配置H5
        //[SBConfigureManager configure];
    }
    
    ///退出登录的操作
    @objc func logout(isDelay: Bool = true, block: (()->())?) -> () {
        
    }
}


//MARK: - === 其他
extension AppDelegate {
    
    //MARK: - ===== 视频播放一些代码
    //func application(_ application: UIApplication, shouldAllowExtensionPointIdentifier extensionPointIdentifier: UIApplication.ExtensionPointIdentifier) -> Bool {
    //    return false
    //}
    // 当应用即将进入非活动状态时执行
    func applicationWillResignActive(_ application: UIApplication) {
        // *让app接受远程事件控制，及锁屏是控制版会出现播放按钮
        UIApplication.shared.beginReceivingRemoteControlEvents()
        // *后台播放代码
        let session = AVAudioSession.sharedInstance()
        do {
            try session.setActive(true, options: AVAudioSession.SetActiveOptions.notifyOthersOnDeactivation)
        }catch {
            
        }
        do {
            try session.setCategory(AVAudioSession.Category.playAndRecord)
        }catch {
            do {
                try session.setCategory(AVAudioSession.Category.playback)
            }catch {
                
            }
        }
    }
    
    // 当应用进入后台时执行  或者应用在前台时被强制关闭时执行
    func applicationDidEnterBackground(_ application: UIApplication) {
        var bgTaskID : UIBackgroundTaskIdentifier!
        bgTaskID = application.beginBackgroundTask {
            //不管有没有完成，结束 background_task 任务
            application.endBackgroundTask(bgTaskID)
            bgTaskID = UIBackgroundTaskIdentifier.invalid
        }
        
        //获取未读计数
        let unReadCount = self.unReadMesNum
        /*NSArray *convs = [[TIMManager sharedInstance] getConversationList];
        for (TIMConversation *conv in convs) {
            if([conv getType] == TIM_SYSTEM){
                continue;
            }
            unReadCount += [conv getUnReadMessageNum];
        }
        */
        UIApplication.shared.applicationIconBadgeNumber = unReadCount
        
        // 毛玻璃 保证安全
        if self.viewEffect == nil {
            let effect = UIBlurEffect.init(style: UIBlurEffect.Style.light)
            let viewEf = UIVisualEffectView.init(effect: effect)
            viewEf.frame = UIScreen.main.bounds
            self.viewEffect = viewEf
            self.window?.addSubview(viewEf)
        }
        // 实现如下代码，才能使程序处于后台时被杀死后调用applicationWillTerminate:方法
        UIApplication.shared.beginBackgroundTask { }
        //进入后台时重置应用的角标
        //self.resetApplicationIconBadgeNumber()
    }
    
    // 当应用即将从后台进入前台时执行，重新启动应用时并不执行，除了此demo演示的特殊情况
    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        if (self.viewEffect != nil) {
            self.viewEffect?.removeFromSuperview()
            self.viewEffect = nil
        }
    }
    
    // APP进入前台 变得活跃 //当应用进入活动状态时执行
    func applicationDidBecomeActive(_ application: UIApplication) {
        ///毛玻璃
        if (self.viewEffect != nil) {
            self.viewEffect?.removeFromSuperview()
            self.viewEffect = nil
        }
    }
    
    // 应用即将停止 //应用被杀死时调用
    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        
    }
    
    /// 在这里写支持的旋转方向，为了防止横屏方向，应用启动时候界面变为横屏模式
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.portrait
    }
    
    //这个方法是为了进入后台时清除应用的角标，同时又不清除之前发送的通知内容
    func resetApplicationIconBadgeNumber() -> () {
        //使用这个方法清除角标，如果置为0的话会把之前收到的通知内容都清空；置为-1的话，不但能保留以前的通知内容，还有角标消失动画，iOS10-以前这样设置是没有作用的 ，iOS10+之后才有效果 。
        if #available(iOS 11.0, *) {
            UIApplication.shared.applicationIconBadgeNumber = -1
        }else{
            //这个发送本地通知的操作是为了解决在iOS10-之前清除角标的同时可以保留通知内容的问题
            //    这个清除角标的操作只在进入后台时执行才会造成：应用在前台时被强制关闭后，立马重启应用后会调用方法applicationWillEnterForeground:，正常情况下重新启动应用时并不执行它；
            let clearEpisodeNotification = UILocalNotification()
            clearEpisodeNotification.fireDate = Date(timeIntervalSinceNow: 1)
            clearEpisodeNotification.applicationIconBadgeNumber = -1 //如果无效可以尝试调大时间
            UIApplication.shared.scheduleLocalNotification(clearEpisodeNotification)
        }
        /*
        1.本地推送UILocalNotification的applicationIconBadgeNumber属性只会影响角标的显示，不会影响通知栏的通知处理。

               1）当applicationIconBadgeNumber>0时，角标会随applicationIconBadgeNumber而变化。

               2）当applicationIconBadgeNumber＝0时，角标维持推送前状态不变。

               3）当applicationIconBadgeNumber<0时，角标置0不显示。

         2.远程推送的badge字段，只会影响角标的显示，不会影响通知栏的通知处理。

              1）当badge>0时，角标会随badge而变化。

              2）当badge＝0时，角标维持不变。

              3）当badge<0时，角标维持不变。

        3.UIApplication的applicationIconBadgeNumber属性既会影响角标的显示，又会影响通知栏通知的处理。

              1）当applicationIconBadgeNumber>0时，角标会随之变化，通知栏通知不变。

              2）当applicationIconBadgeNumber＝0时，角标变为0不显示，通知栏通知清空。

              3）当applicationIconBadgeNumber<0时，角标变为0不显示，通知栏通知清空。
        */
    }
}


//MARK: - ==== 推送相关
extension AppDelegate : UNUserNotificationCenterDelegate {
    /// - ==== 推送时 获取DeviceToken 进行上传
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        self.deviceToken = deviceToken
        /*
        var deviceTokenStr = ""
        if #available(iOS 13.0, *) {
            if (![deviceToken isKindOfClass:[NSData class]]) return;
            const unsigned *tokenBytes = [deviceToken bytes];
            deviceTokenStr = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                                  ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                                  ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                                  ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
        }else{
            deviceTokenStr = [deviceToken description];
            for (NSString *symbol in @[@" ", @"<", @">", @"-"]) {
                deviceTokenStr = [deviceTokenStr stringByReplacingOccurrencesOfString:symbol withString:@""];
            }
        }
        DTLog(@"deviceToken ====>:%@",deviceTokenStr);
        */
    }
    
    //iOS10以下使用这两个方法接收通知，
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        let systemVersion = (UIDevice.current.systemVersion as NSString).doubleValue
        var options = UIBackgroundFetchResult.newData
        if systemVersion < 10 {
            //self.UPushDidReceiveRemoteNotification(userInfo: userInfo)
            //应用处于前台时的远程推送接受
            let allKeys = (userInfo as NSDictionary).allKeys
            var isTiaoGuo = true
            if allKeys.count > 0 {
                let type = userInfo["type"]
                if type != nil {///友盟推送
                    var type1 = 0
                    if type is String {
                        type1 = (type as? NSString)?.integerValue ?? 0
                    }else if type is NSNumber {
                        type1 = (type as? NSNumber)?.intValue ?? 0
                    }
                    switch type1 {
                    case 0:
                        break
                    default:
                        isTiaoGuo = false
                        break
                    }
                    if isTiaoGuo {
                        options = UIBackgroundFetchResult.noData
                    }
                }
            }
        }
        completionHandler(options)
    }
    
    //
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        self.UPushDidReceiveRemoteNotification(userInfo: userInfo)
        //    self.userInfo = userInfo;
        //    //定制自定的的弹出框
        //    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
        //    {
        //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"标题"
        //                                                            message:@"Test On ApplicationStateActive"
        //                                                           delegate:self
        //                                                  cancelButtonTitle:@"确定"
        //                                                  otherButtonTitles:nil];
        //
        //        [alertView show];
        //
        //    }
    }
    
    ///iOS10新增：处理后台点击通知的代理方法
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        if response.notification.request.trigger is UNPushNotificationTrigger {
            //应用处于后台时的远程推送接受
            //必须加这句代码
            self.UPushDidReceiveRemoteNotification(userInfo: userInfo)
        }else{
            //应用处于后台时的本地推送接受
        }
    }
    //iOS10新增：处理前台收到通知的代理方法
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        //当应用处于前台时提示设置，需要哪个可以设置哪一个
        var options = UNNotificationPresentationOptions.init(rawValue: UNNotificationPresentationOptions.sound.rawValue|UNNotificationPresentationOptions.badge.rawValue|UNNotificationPresentationOptions.alert.rawValue)
        if notification.request.trigger is UNPushNotificationTrigger {
            //应用处于前台时的远程推送接受
            //关闭U-Push自带的弹出框
            //self.UPushDidReceiveRemoteNotification(userInfo: userInfo)
            //应用处于前台时的远程推送接受
            let allKeys = (userInfo as NSDictionary).allKeys
            var isTiaoGuo = true
            if allKeys.count > 0 {
                let type = userInfo["type"]
                if type != nil {///友盟推送
                    var type1 = 0
                    if type is String {
                        type1 = (type as? NSString)?.integerValue ?? 0
                    }else if type is NSNumber {
                        type1 = (type as? NSNumber)?.intValue ?? 0
                    }
                    switch type1 {
                    case 0:
                        break
                    default:
                        isTiaoGuo = false
                        break
                    }
                    if isTiaoGuo {
                        options = UNNotificationPresentationOptions.init(rawValue: UNNotificationPresentationOptions.sound.rawValue|UNNotificationPresentationOptions.badge.rawValue)
                    }
                }
            }
        }else{
            //应用处于前台时的本地推送接受
        }
        completionHandler(options)
    }
    
    //推送的后期处理
    func UPushDidReceiveRemoteNotification(userInfo: [AnyHashable : Any], isOk: Bool = false) -> () {
        
    }

    /*///本地 前台弹窗
    - (void)bendiQianTaiTanChuan:(NSDictionary *)userInfo {
        EBBannerView *banner = [EBBannerView bannerWithBlock:^(EBBannerViewMaker *make) {
            //make.style = EBBannerViewStyleiOS9;
            make.content = userInfo[@"aps"][@"alert"];
            make.object = userInfo;
        }];
        [banner show];
    }*/
}


//MARK: - ==== MDHWKWebViewManager js交互
extension AppDelegate {
    ///js交互的监听
    fileprivate func _showWeb_js() -> () {
        kMDHWebVCM().blockPushNextVc = { [weak self] (model) in
                if let weakSelf = self {
                    weakSelf.pushVc(model: model)
                }
        }
        /*
        kMDHWebVCM().blockPushScriptNextVc = {
            [weak self] (userContentController, message, webView) in
            if let weakSelf = self {
                let name = message.name
                let services = weakSelf.services
                let user = services.client.currentUser()
                switch name {
                case "getUserAccount":
                    let js_str = "sendUserAccount('\(user.perfect_number)')"
                    webView?.evaluateJavaScript(js_str, completionHandler: { (result, error) in
                        #if DEBUG
                        print(error as Any)
                        #endif
                    })
                case "pageJumpRecharge":
                    let vm = MMWalletRechargeViewModel.init(services: services, params: [AnyHashable : Any]())
                    services.push(vm, animated: true)
                case "getAppKey":
                    let js_str = "sendAppKey('\(user.user_sig)')"
                    webView?.evaluateJavaScript(js_str, completionHandler: { (result, error) in
                        #if DEBUG
                        print(error as Any)
                        #endif
                    })
               case "getRoomId":
                    let room_id = kMDHCMMQ().room_id
                    let js_str = "sendRoomId('\(room_id)')"
                    webView?.evaluateJavaScript(js_str, completionHandler: { (result, error) in
                        #if DEBUG
                        print(error as Any)
                        #endif
                    })
                case "goShare":///分享
                    let body = message.body
                    if body is NSDictionary {
                        let model = MMShareInfoModel.mj_object(withKeyValues: body) ?? MMShareInfoModel()
                        let view_s = MMChatroomShareView(vm: nil)
                        view_s.data = model
                        view_s.show_view()
                    }
                default:
                    break
                }
            }
        }*/
    }
    
    /*
     ///进行页面的跳转 及其他的操作
    */
    fileprivate func pushVc(model: MDHWKWebViewModel) -> () {
        
    }
    
    ///跳转一级界面
    fileprivate func popOneInterface(index: Int, model: MDHWKWebViewModel) -> () {
        
    }
}


//MARK: - =====
extension AppDelegate {
    //swift引用OC方法时，最好根据系统代码提示来写
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
        //其他第三方回调:
        return true
    }
    //注意，swift4.2版本开始，系统方法修改为：
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        //如果使用了Universal Links ，此方法必写
        //其他第三方回调:
        return true
    }
    ///
    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        return self.setupURLScheme(url: url, options: nil)
    }
    /// NOTE: 9.0以后使用新API接口
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        return self.setupURLScheme(url: url, options: options)
    }
    ///URL Scheme处理 // NOTE: 9.0以前API接口
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        return self.setupURLScheme(url: url, options: annotation)
    }
    
    ///URL Scheme处理 回调处理
    func setupURLScheme(url: URL, options: Any?) -> Bool {
        /*
        let scheme = url.scheme ?? ""
        #if DEBUG
        print(scheme)
        #endif
        */
        
        ///APP内部的协议
        let absoluteString = url.absoluteString as NSString
        if absoluteString.hasPrefix(kMDHPTURLSchemes) {
            self.curAppUrlScheme = url.absoluteString
            return true
        }
        return true
    }
}


//MARK: - ==== MQTT 相关
extension AppDelegate {
    ///链接MQTT
    func mqtt_start() -> () {
        
    }
}


//MARK: - ===== 小界面 弹窗
extension AppDelegate {
    ///添加 视图的弹窗
    @objc func add_activeAlertVc() -> () {
        
    }
    
    ///检测 系统通知是否开启了
    @objc func show_messageNotification() -> () {
        
    }
    
    ///展示青少年模式
    @objc func show_adolescent(isStart: Bool = false) -> () {
        
    }
    
    ///苹果内购查询 支付
    fileprivate func showAppleIn_AppPurchase() -> () {
        
    }
}



//MARK: creatShortcutItem
extension AppDelegate {
    ///creatShortcutItem ====>
    fileprivate func creatShortcutItem() -> () {
        //创建系统风格的icon
        if #available(iOS 9.0, *) {
            //let schemes = kMDHPTURLSchemes
            /*let fenxiang = UIApplicationShortcutIcon.init(type: UIApplicationShortcutIcon.IconType.share)
            let fenxiangItem = UIApplicationShortcutItem.init(type: "systemMsg", localizedTitle: "分享", localizedSubtitle: "分享APP", icon: fenxiang, userInfo: nil)*/
            
            ///搜索
            //let sousuo = UIApplicationShortcutIcon.init(type: UIApplicationShortcutIcon.IconType.search)
            ///我的钱包
            let wdqbItem = UIApplicationShortcutItem.init(type: "MyPurse", localizedTitle: "我的钱包")
            ///消息
            let xiaoxiItem = UIApplicationShortcutItem.init(type: "message", localizedTitle: "消息")
            ///搜索
            let sousuoItem = UIApplicationShortcutItem.init(type: "search0", localizedTitle: "搜索房间")
            let sousuoItem1 = UIApplicationShortcutItem.init(type: "search1", localizedTitle: "搜索用户")
            UIApplication.shared.shortcutItems = [wdqbItem, xiaoxiItem, sousuoItem, sousuoItem1]
        } else {
            // Fallback on earlier versions
        }
    }
    
    ///下一步的操作 
    fileprivate func dealWithShortcut(type: String) -> () {
        print("----- \(type) ------")
        var dict = [AnyHashable : Any]()
        switch type {
        case "systemMsg":
            dict["type"] = 1
        case "search0":
            dict["type"] = 100
        case "search1":
            dict["type"] = 101
        case "MyPurse":
            dict["type"] = 102
        case "message":
            dict["type"] = 103
        default:
            break
        }
        if dict.count > 0 {
            //let model = MDHWKWebViewModel()
            self.UPushDidReceiveRemoteNotification(userInfo: dict)
        }
    }
    
    // 当app已启动, 点击shortcutItem回调
    @available(iOS 9.0, *)
    func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
        self.dealWithShortcut(type: shortcutItem.type)
        completionHandler(true)
    }
}
